package com.wjf.birdfish.action;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.opensymphony.xwork2.Action;
import com.wjf.birdfish.commons.SRMException;
import com.wjf.birdfish.util.SecurityContext;
import com.wjf.birdfish.util.SecurityContextHolder;

/**
 * 登录和注销的Action
 * 
 * @author <a href="malito:tongys@tydic.com">童永胜</a>
 */
public class LoginAction extends BaseAction {

	private static final long serialVersionUID = 1L;

	private String loginName;
	private String loginPwd;
	private String agentIp;
	private String duns;
	private String area;


	public void prepare() throws Exception {
		clearErrorsAndMessages();
	}

	public String execute() throws Exception {
		return login();
	}

	public String login() throws Exception {
		SecurityContext context = SecurityContextHolder.getContext();
		context.setArea(this.getArea());
		context.setProjectName(request.getContextPath());
		//agentIp = context.getAgentIp();
//		SysUserAcct sysUserAcct = sysUserAcctService.login(loginName, loginPwd);
//		if (sysUserAcct != null) {
//			if ("0".equals(sysUserAcct.getDeleteFlag())) {
//				saveMessage("该帐号已经被管理员置为无效,不允许登录系统！");
//				return INPUT;
//			} else {
//				//如果用户已登录
//				UserLoginContext userLoginContext = UserLoginContext.getInstance();
//				Map<String,Long> loginUserList = userLoginContext.getLoginedUserList();
//				String userId=sysUserAcct.getUserId();
//				if(loginUserList.containsKey(userId)){
//					saveMessage("帐号已登录，无法再登录！");
//					return INPUT;
//				}
//				userLoginContext.addUser(userId);
//				
//				SysUserLog sysUserLog = new SysUserLog();
//				sysUserLog.setIpAddress(request.getRemoteAddr());
//				sysUserLog.setLogTime(new Date());
//				sysUserLog.setLogType("UNKNOW");
//				sysUserLog.setLogContent("用户登录");
//				sysUserLog.setUserAccount(loginName);
//
//				sysUserLogService.saveSysUserLog(sysUserLog);
//
//				session.setAttribute(Constants.SESSION_USER_KEY, sysUserAcct);
//				List<SysResource> set = new ArrayList<SysResource>();
//				List<SysResource> topSet = new ArrayList<SysResource>();
//				Set<SysUserRoleRelation> sysUserRoleRelationSet = sysUserAcct.getSysUserRoles();
//				// System.out.println("sysUserRoleRelationSet.size()="
//				// + sysUserRoleRelationSet.size());
//				for (Iterator<SysUserRoleRelation> it = sysUserRoleRelationSet
//						.iterator(); it.hasNext();) {
//					SysUserRoleRelation sysUserRoleRelation = it.next();
//					List<SysResource> srList = sysResourceService
//							.getSysResourceList(
//									"from SysResource a where a.resId in ("
//											+ "select b.resId from SysRoleResFunc b where b.roleId=?) order by resOrder",
//									sysUserRoleRelation.getSysUserRole()
//											.getRoleId());
//					for (SysResource sr : srList) {
//						if (sr.getResParentId().equals("0"))
//							topSet.add(sr);
//						else
//							set.add(sr);
//					}
//				}
//				duns = sysDataPermissionService
//						.getDataPermissionByUserAccount(loginName);
//				String provsId = duns.substring(0, 2);
//				int provsType = sysDataPermissionService.getProvsType(provsId);
//				session.setAttribute("duns", duns);
//				session.setAttribute("topSet", topSet);
//				session.setAttribute("set", set);
//				session.setAttribute("loginName", loginName);
//				session.setAttribute("userId", sysUserAcct.getUserId());
////				sysUserLog.setIpAddress(agentIp);
////				sysUserLog.setLogContent("登录系统");
////				sysUserLog.setLogType("ADD");
////				sysUserLog.setLogTime(new Date());
////				sysUserLog.setUserAccount(loginName);
////				//sysUserLog.setLogId(Dbid.getID());
////				sysUserLogService.saveSysUserLog(sysUserLog);
//				// this.log(sysUserLog);
//				context.setSysUser(sysUserAcct);
//				context.setAgentIp(request.getRemoteAddr());
//				context.setDuns(new String[] { duns });
//				context.setLoginTime(sysUserLog.getLogTime());
//				context.setLogined(true);
//				context.setProvsType(provsType + "");
////				ServletContext application = session.getServletContext();
////				List<String> onlineUserList =  (List<String>) application.getAttribute("onlineUserList");
//				/*boolean isLogin = false;
//				if(onlineUserList != null){
//					for(String loginId:onlineUserList){
//						if(loginId.equalsIgnoreCase(loginName)){
//							isLogin = true;
//						}
//					}
//				}
//				if(!isLogin){
////					session.setAttribute("onlineUserBindingListener",
////							new OnlineUserBindingListener(loginName));
//					return SUCCESS;
//				}else{
//					saveMessage("帐号已登录，无法再登录！");
//					return INPUT;
//				}*/
//				return SUCCESS;
//			}
//		} else {
//			saveMessage("帐号或密码错误,请重新输入！");
//			return INPUT;
//		}
		return Action.SUCCESS;
	}

	public String logout() throws SRMException {
		SecurityContext context = SecurityContextHolder.getContext();
//		SysUserAcct sysUserAcct = null;
//		try {
//			sysUserAcct = (SysUserAcct) session
//					.getAttribute(Constants.SESSION_USER_KEY);
//		} catch (Exception e) {
//			LOG.error("Can not get Session,may be Session is already invalidated");
//		}
//		if(sysUserAcct != null){
//			SysUserLog sysUserLog = new SysUserLog();
//			sysUserLog.setIpAddress(context.getAgentIp());
//			sysUserLog.setLogTime(new Date());
//			sysUserLog.setLogType("UNKNOW");
//			sysUserLog.setLogContent("用户退出");
//			sysUserLog.setUserAccount(sysUserAcct.getUserAcct());
//			sysUserLogService.saveSysUserLog(sysUserLog);
//			session.invalidate();
//			
//			//从登录用户队列删除
//			UserLoginContext userLoginContext =UserLoginContext.getInstance();
//			String userId=sysUserAcct.getUserId();
//			userLoginContext.removeUser(userId);
//		}
		
		
		
//		ServletContext application = session.getServletContext();
//		List<String> onlineUserList =  (List<String>) application.getAttribute("onlineUserList");
//		if(onlineUserList != null && onlineUserList.size() > 0){
//			onlineUserList.remove(sysUserAcct.getUserAcct());
//		}
//		application.setAttribute("onlineUserList", onlineUserList);
		return SUCCESS;
	}
	public String imExsits(){
		HttpSession session = ((HttpServletRequest) request).getSession();
//		SysUserAcct sysUserAcct = null;
//		try {
//			sysUserAcct = (SysUserAcct) session
//					.getAttribute(Constants.SESSION_USER_KEY);
//			if(sysUserAcct !=null){
//				UserLoginContext userLoginContext =UserLoginContext.getInstance();
//				String userId=sysUserAcct.getUserId();
//				userLoginContext.updateUserTime(userId, new Date().getTime());
//			}
//		} catch (Exception e) {
//			LOG.error("Can not get Session,may be Session is already invalidated");
//		}  
		
		return Action.SUCCESS;
	}  

	/* ================== setter ================= */

	public String getLoginName() {
		return loginName;
	}

	public void setLoginName(String loginName) {
		this.loginName = loginName;
	}

	public String getLoginPwd() {
		return loginPwd;
	}

	public void setLoginPwd(String loginPwd) {
		this.loginPwd = loginPwd;
	}

	public String getAgentIp() {
		return agentIp;
	}

	public void setAgentIp(String agentIp) {
		this.agentIp = agentIp;
	}


	public String getArea() {
		return area;
	}

	public void setArea(String area) {
		this.area = area;
	}

}